import {
  config
} from '../config.js';
import {
  Token
} from '../models/token.js';
import {
  Base64
} from './base64'

const tips = {
  1: '抱歉，出现了一个错误',
  1000: '输入参数错误',
  1001: '输入的json格式不正确',
  1002: '找不到资源',
  1003: '未知错误',
  1004: '禁止访问',
  1005: 'appkey无效，请前往www.7yue.pro申请',
  1006: '服务器内部错误',
  2000: '你已经点过赞了',
  2001: '你还没点过赞',
  3000: '期刊不存在'
}

class HTTP {
  request({
    url,
    data = {},
    method = "GET"
  }) {
    return new Promise((resolve, reject) => {
      this._request(url, resolve, reject, data, method)
    })
  }

  _request(url, resolve, reject, data = {}, method = "GET", noRefetch = false) {

    wx.request({
      url: `${config.api_base_url}${url}`,
      method: method,
      data: data,
      header: {
        'content-type': 'application/json',
        Authorization: this._encode()
        // 'appkey': config.appkey
      },
      success: (res) => {
        // startsWith
        // endsWith
        const code = res.statusCode.toString();
        if (code.startsWith('2')) {
          resolve(res.data);

        } else {
          if (code == "403") {
            if (!noRefetch) {
              this._refetch(
                url,
                resolve,
                reject,
                data,
                method
              )
            } else {
              reject();
              const error_code = res.data.error_code;
              this._show_error(error_code);
            }
          }
        }
      },
      fail: (err) => {
        reject();
        this._show_error(1);
      }
    })
  }

  _show_error(error_code) {
    if (!error_code) {
      error_code = 1;
    }
    const tip = tips[error_code];
    wx.showToast({
      title: tip ? tip : tips[1],
      icon: 'none',
      duration: 2000
    })
  }

  _refetch(...param) {
    const token = new Token();
    token.getToken((token) => {
      this._request(...param, true);
    })
  }

  _encode() {
    const token = wx.getStorageSync('token');
    const base64 = new Base64().encode(token + ':');
    return 'Basic ' + base64;
  }
}

export {
  HTTP
}